<template>
  <div class="card-detail-container">
    <div v-if="loading" class="loading-container">
      <div class="spinner"></div>
      <p>加载中...</p>
    </div>
    
    <div v-else-if="error" class="error-container">
      <p>{{ error }}</p>
      <button @click="fetchCardData" class="btn btn-primary">重试</button>
    </div>
    
    <div v-else class="card-content">
      <div class="card-header">
        <div class="card-meta">
          <span class="card-chapter">{{ card.chapter }}</span>
          <span class="card-difficulty" :class="difficultyClass">
            {{ difficultyText }}
          </span>
        </div>
        <h1 class="card-title">{{ card.title }}</h1>
        <div class="card-tags">
          <span v-for="tag in card.tags" :key="tag" class="tag">{{ tag }}</span>
        </div>
      </div>
      
      <div class="card-body">
        <div class="card-content-section">
          <h2>知识点</h2>
          <div v-html="card.content" class="content-html"></div>
        </div>
        
        <div class="card-examples-section" v-if="card.examples && card.examples.length > 0">
          <h2>示例</h2>
          <div v-for="(example, index) in card.examples" :key="index" class="example-item">
            <div v-html="example" class="content-html"></div>
          </div>
        </div>
      </div>
      
      <div class="card-actions">
        <button 
          @click="toggleBookmark" 
          class="btn" 
          :class="isBookmarked ? 'btn-warning' : 'btn-outline-warning'"
        >
          <i class="icon" :class="isBookmarked ? 'icon-bookmark-fill' : 'icon-bookmark'"></i>
          {{ isBookmarked ? '已收藏' : '收藏' }}
        </button>
        
        <button @click="generateExercises" class="btn btn-primary">
          <i class="icon icon-quiz"></i>
          生成练习题
        </button>
      </div>
      
      <!-- 笔记部分 -->
      <div class="notes-section">
        <h2>我的笔记</h2>
        <div v-if="userNote" class="existing-note">
          <div class="note-content" v-html="userNote.content"></div>
          <div class="note-actions">
            <button @click="editingNote = true" class="btn btn-sm btn-outline-primary">
              <i class="icon icon-edit"></i> 编辑
            </button>
            <button @click="deleteNote" class="btn btn-sm btn-outline-danger">
              <i class="icon icon-delete"></i> 删除
            </button>
          </div>
        </div>
        
        <div v-if="!userNote || editingNote" class="note-editor">
          <textarea 
            v-model="noteContent" 
            placeholder="添加笔记..." 
            rows="4"
            class="form-control"
          ></textarea>
          <div class="editor-actions">
            <button @click="cancelNoteEdit" class="btn btn-sm btn-outline-secondary">
              取消
            </button>
            <button @click="saveNote" class="btn btn-sm btn-primary">
              保存笔记
            </button>
          </div>
        </div>
      </div>
      
      <!-- 相关卡片 -->
      <div v-if="relatedCards.length > 0" class="related-cards">
        <h2>相关知识点</h2>
        <div class="related-cards-list">
          <div 
            v-for="relatedCard in relatedCards" 
            :key="relatedCard._id"
            class="related-card-item"
            @click="navigateToCard(relatedCard._id)"
          >
            <h3>{{ relatedCard.title }}</h3>
            <div class="related-card-meta">
              <span class="related-card-chapter">{{ relatedCard.chapter }}</span>
              <span class="related-card-difficulty" :class="getDifficultyClass(relatedCard.difficulty)">
                {{ getDifficultyText(relatedCard.difficulty) }}
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useCardStore } from '@/store/card';
import { useUserStore } from '@/store/user';
import { cardApi } from '@/services/api';
import { userApi } from '@/services/api';
import { exerciseApi } from '@/services/api';

export default {
  name: 'CardDetailView',
  setup() {
    const route = useRoute();
    const router = useRouter();
    const cardStore = useCardStore();
    const userStore = useUserStore();
    
    // 状态
    const card = ref({});
    const loading = ref(true);
    const error = ref(null);
    const relatedCards = ref([]);
    const isBookmarked = ref(false);
    const userNote = ref(null);
    const noteContent = ref('');
    const editingNote = ref(false);
    
    // 计算属性
    const difficultyClass = computed(() => {
      return getDifficultyClass(card.value.difficulty);
    });
    
    const difficultyText = computed(() => {
      return getDifficultyText(card.value.difficulty);
    });
    
    // 获取卡片数据
    const fetchCardData = async () => {
      loading.value = true;
      error.value = null;
      
      try {
        // 获取卡片详情
        const cardId = route.params.id;
        console.log(`[fetchCardData] 开始获取卡片 ${cardId} 的详情`);
        
        const response = await cardApi.getById(cardId);
        console.log(`[fetchCardData] 获取到卡片详情:`, response.data);
        card.value = response.data;
        
        // 获取相关卡片
        console.log(`[fetchCardData] 开始获取相关卡片`);
        const relatedResponse = await cardApi.getRelated(cardId);
        console.log(`[fetchCardData] 获取到相关卡片:`, relatedResponse.data);
        relatedCards.value = relatedResponse.data;
        
        // 检查是否已收藏
        if (userStore.isAuthenticated) {
          console.log(`[fetchCardData] 获取用户书签`);
          const bookmarksResponse = await userApi.getBookmarks();
          console.log(`[fetchCardData] 获取到书签:`, bookmarksResponse.data);
          isBookmarked.value = bookmarksResponse.data.some(bookmark => bookmark._id === cardId);
          console.log(`[fetchCardData] 卡片是否已收藏:`, isBookmarked.value);
          
          // 获取用户笔记
          console.log(`[fetchCardData] 获取用户笔记`);
          const notesResponse = await userApi.getNotes();
          console.log(`[fetchCardData] 获取到笔记:`, notesResponse.data);
          const cardNote = notesResponse.data.find(note => note.cardId._id === cardId);
          if (cardNote) {
            console.log(`[fetchCardData] 找到卡片相关笔记:`, cardNote);
            userNote.value = cardNote;
            noteContent.value = cardNote.content;
          } else {
            console.log(`[fetchCardData] 未找到卡片相关笔记`);
            userNote.value = null;
            noteContent.value = '';
          }
        }
      } catch (err) {
        console.error('[fetchCardData] 获取卡片详情失败:', err);
        error.value = err.message || '获取卡片详情失败';
      } finally {
        loading.value = false;
      }
    };
    
    // 切换收藏状态
    const toggleBookmark = async () => {
      try {
        if (isBookmarked.value) {
          await userApi.removeBookmark(card.value._id);
          isBookmarked.value = false;
        } else {
          await userApi.addBookmark(card.value._id);
          isBookmarked.value = true;
        }
      } catch (err) {
        console.error('更新收藏状态失败:', err);
      }
    };
    
    // 保存笔记
    const saveNote = async () => {
      try {
        if (userNote.value) {
          // 更新现有笔记
          await userApi.updateNote(userNote.value._id, {
            content: noteContent.value,
            cardId: card.value._id
          });
          userNote.value.content = noteContent.value;
        } else {
          // 创建新笔记
          const response = await userApi.addNote({
            content: noteContent.value,
            cardId: card.value._id
          });
          userNote.value = response.data;
        }
        editingNote.value = false;
      } catch (err) {
        console.error('保存笔记失败:', err);
      }
    };
    
    // 删除笔记
    const deleteNote = async () => {
      if (!userNote.value) return;
      
      try {
        await userApi.deleteNote(userNote.value._id);
        userNote.value = null;
        noteContent.value = '';
      } catch (err) {
        console.error('删除笔记失败:', err);
      }
    };
    
    // 取消编辑笔记
    const cancelNoteEdit = () => {
      if (userNote.value) {
        noteContent.value = userNote.value.content;
      } else {
        noteContent.value = '';
      }
      editingNote.value = false;
    };
    
    // 生成练习题
    const generateExercises = async () => {
      try {
        await exerciseApi.generate(card.value._id, {
          types: ['multiple', 'fill', 'code'],
          count: 3
        });
        router.push(`/exercises?cardId=${card.value._id}`);
      } catch (err) {
        console.error('生成练习题失败:', err);
      }
    };
    
    // 导航到其他卡片
    const navigateToCard = (cardId) => {
      router.push(`/cards/${cardId}`);
    };
    
    // 获取难度样式类
    const getDifficultyClass = (difficulty) => {
      switch (difficulty) {
        case 1: return 'difficulty-easy';
        case 2: return 'difficulty-medium';
        case 3: return 'difficulty-hard';
        default: return 'difficulty-medium';
      }
    };
    
    // 获取难度文本
    const getDifficultyText = (difficulty) => {
      switch (difficulty) {
        case 1: return '简单';
        case 2: return '中等';
        case 3: return '困难';
        default: return '中等';
      }
    };
    
    // 组件挂载时获取数据
    onMounted(() => {
      fetchCardData();
    });
    
    return {
      card,
      loading,
      error,
      relatedCards,
      isBookmarked,
      userNote,
      noteContent,
      editingNote,
      difficultyClass,
      difficultyText,
      fetchCardData,
      toggleBookmark,
      saveNote,
      deleteNote,
      cancelNoteEdit,
      generateExercises,
      navigateToCard,
      getDifficultyClass,
      getDifficultyText
    };
  }
};
</script>

<style scoped>
.card-detail-container {
  max-width: 900px;
  margin: 0 auto;
  padding: 20px;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(0, 0, 0, 0.1);
  border-radius: 50%;
  border-top-color: #3498db;
  animation: spin 1s ease-in-out infinite;
  margin-bottom: 15px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.error-container {
  text-align: center;
  padding: 30px;
  background-color: #fff3f3;
  border-radius: 8px;
  margin: 20px 0;
}

.card-header {
  margin-bottom: 20px;
}

.card-meta {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
}

.card-chapter {
  background-color: #e3f2fd;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.9rem;
}

.card-difficulty {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.9rem;
}

.difficulty-easy {
  background-color: #e8f5e9;
  color: #2e7d32;
}

.difficulty-medium {
  background-color: #fff8e1;
  color: #ff8f00;
}

.difficulty-hard {
  background-color: #ffebee;
  color: #c62828;
}

.card-title {
  font-size: 1.8rem;
  margin: 10px 0;
}

.card-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 15px;
}

.tag {
  background-color: #f1f1f1;
  padding: 4px 8px;
  border-radius: 16px;
  font-size: 0.8rem;
}

.card-body {
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.card-content-section h2,
.card-examples-section h2 {
  font-size: 1.4rem;
  margin-bottom: 15px;
  color: #333;
}

.content-html {
  line-height: 1.6;
}

.example-item {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #eee;
}

.card-actions {
  display: flex;
  gap: 10px;
  margin-bottom: 30px;
}

.notes-section {
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 30px;
}

.notes-section h2 {
  font-size: 1.4rem;
  margin-bottom: 15px;
  color: #333;
}

.existing-note {
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 15px;
}

.note-content {
  margin-bottom: 10px;
  line-height: 1.6;
}

.note-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.note-editor {
  margin-top: 15px;
}

.editor-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 10px;
}

.related-cards h2 {
  font-size: 1.4rem;
  margin-bottom: 15px;
  color: #333;
}

.related-cards-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 15px;
}

.related-card-item {
  background-color: white;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: transform 0.2s, box-shadow 0.2s;
}

.related-card-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.related-card-item h3 {
  font-size: 1.1rem;
  margin-bottom: 10px;
}

.related-card-meta {
  display: flex;
  gap: 10px;
  font-size: 0.8rem;
}

.related-card-chapter {
  background-color: #e3f2fd;
  padding: 2px 6px;
  border-radius: 4px;
}

.btn {
  display: inline-flex;
  align-items: center;
  gap: 5px;
  padding: 8px 16px;
  border-radius: 4px;
  font-weight: 500;
  cursor: pointer;
  border: none;
  transition: background-color 0.2s;
}

.btn-primary {
  background-color: #1976d2;
  color: white;
}

.btn-primary:hover {
  background-color: #1565c0;
}

.btn-warning {
  background-color: #ff9800;
  color: white;
}

.btn-warning:hover {
  background-color: #f57c00;
}

.btn-outline-warning {
  background-color: transparent;
  color: #ff9800;
  border: 1px solid #ff9800;
}

.btn-outline-warning:hover {
  background-color: #fff3e0;
}

.btn-outline-primary {
  background-color: transparent;
  color: #1976d2;
  border: 1px solid #1976d2;
}

.btn-outline-primary:hover {
  background-color: #e3f2fd;
}

.btn-outline-danger {
  background-color: transparent;
  color: #d32f2f;
  border: 1px solid #d32f2f;
}

.btn-outline-danger:hover {
  background-color: #ffebee;
}

.btn-outline-secondary {
  background-color: transparent;
  color: #757575;
  border: 1px solid #757575;
}

.btn-outline-secondary:hover {
  background-color: #f5f5f5;
}

.btn-sm {
  padding: 4px 8px;
  font-size: 0.9rem;
}

.form-control {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-family: inherit;
  font-size: inherit;
  resize: vertical;
}

.form-control:focus {
  outline: none;
  border-color: #1976d2;
  box-shadow: 0 0 0 2px rgba(25, 118, 210, 0.2);
}
</style> 